﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.Mvc;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Helper;
using System.Linq;
using ShopB2C.ViewModels;

namespace ShopB2C.Controllers.Manager
{
    public partial class ProductController : BaseController
    {

        public ActionResult PreView([DefaultValue(0)]int productId) {
            ProductEntity product = _productOperate.GetBasicById(productId);
            if (product == null) {
                return Content("没有找到相关商品信息!");
            }
            this.SiteMapPathAdd("编辑" , Url.Action("Edit" , new { ProductId = productId }));

            Dictionary<string , IEnumerable<ProductExtendEntity>> extendProperty = new Dictionary<string , IEnumerable<ProductExtendEntity>>();
            List<ProductExtendEntity> extendList = _productPreView.ProductExtendList(productId);
            var temp = extendList.GroupBy(i => i.ExtendKey , (key , list) => { extendProperty.Add(key , list); return 0; });
            foreach (var i in temp) ;


            return View(new ProductViewModel() {
                ProductView = product,
                PropertyList = _productPreView.PropertyList(productId, null),
                ImageList = _productPreView.GetImageList(productId),
                Details = _productPreView.GetDetails(productId),
                ImageRoot = _imageRoot,
                ExtendProperty = extendProperty
            });
        }
        /// <summary>
        /// 所有商品
        /// </summary>
        [HttpGet]
        public ActionResult ProductList(
            [DefaultValue(1)]int number //页码
            , [DefaultValue(1)]int status //状态
            , [DefaultValue(0)]int classId //所属分类
            , [DefaultValue("")]string key //搜索关键字
             )
        {
            this.SiteMapPathAdd("商品列表");

            int pageCount = 0;
            // 调整恶意状态输入
            status = status < 0 || status > 4 ? 4 : status;

            List<ProductEntity> productList = _productPreView.Search(
                new ProductSearchCondition()
                {
                    Status = (ProductSearchActionType)status ,
                    ClassifyId = classId ,
                    Key = key ,
                    PageIndex = number ,
                    PageSize = 10 ,
                    SortIndex = ProductSortFieldNames.SaleDateTime ,
                    SortDescription = SortDescriptions.DESC ,
                    ProductStatus = 0
                } , out pageCount);

            object pager = this.CreatePager(
                Url.Action("ProductList" , new
                {
                    number = "{0}" ,
                    status = status ,
                    classId = classId ,
                    key = key
                }) , pageCount , number);


            return View(new ProductViewModel()
            {
                ClassifyList = _classify.GetClassifyByModuleKey(_moduleKey) ,
                Classify = new ClassifyEntity() { ClassifyId = classId } ,
                SearchActionTypes = new SelectList(
                    Methods.GetEnumsToList(typeof(ProductSearchActionType)) ,
                    "Value" , "Text" , status) ,
                BatchActionTypes = new SelectList(
                    Methods.GetEnumsToList(typeof(ProductBatchActionType)) ,
                    "Value" , "Text" , 3) ,
                ImageRoot = _imageRoot ,
                ProductList = productList ,
                PageNumber = number ,
                Pager = pager
            });
        }
        /// <summary>
        /// 批量修改商品
        /// </summary>
        [HttpPost]
        public ActionResult ProductBatch()
        {
            this.SiteMapPathAdd("商品批量修改");
            MessageHelper msgHelper = new MessageHelper("productbatch");
            msgHelper.AddBody(0);

            string ac = Request.Form["hidBatchAction"];
            string ids = Request.Form["ckSelect"];
            msgHelper.Required(ac , 0);
            msgHelper.Required(ids , 6);
            if (!msgHelper.IsValid) { return this.MessageResult(msgHelper.CreateMessage()); }

            int pageCount;
            List<ProductEntity> productList = _productPreView.GetProductByIds(ids);
            List<BrandEntity> brandList = _brand.GetBrandList(0 , int.MaxValue , 1 , out pageCount);
            brandList.Insert(0 , new BrandEntity());

            if (bool.Parse(ac))
            {
                ViewData["Active"] = new List<object>() {
                    new { text = "否", value = "0" },
                    new { text = "是", value = "1" }
                };
            }

            return View(new ProductViewModel()
            {
                BatchActionTypes = new SelectList(
                    Methods.GetEnumsToList(typeof(ProductBatchActionType)) ,
                    "Value" , "Text" , 3) ,
                ProductStatus = new SelectList(
                    Methods.GetEnumsToList(typeof(ProductStatus)) ,
                    "Value" , "Text") ,
                BrandList = brandList ,
                ProductList = productList ,
                IsOneByOne = bool.Parse(ac)
            });
        }

        [HttpPost]
        public ActionResult ProductBatchSave()
        {

            MessageHelper msgHelper = new MessageHelper("productbatch");
            msgHelper.AddBody(0);
            string ac = Request.Form["hidBatchAction"];
            string ids = Request.Form["hidProductId"];
            msgHelper.Required(ac , 0);
            msgHelper.Required(ids , 6);
            if (!msgHelper.IsValid) { return this.MessageResult(msgHelper.CreateMessage()); }

            if (bool.Parse(ac))
            {
                this.BatchOneByOne(msgHelper , ids);
            }
            else
            {
                this.BatchTogether(msgHelper , ids);
            }

            return msgHelper.IsValid
                ? this.RedirectToAction("ProductList")
                : this.MessageResult(msgHelper.CreateMessage());
        }

        // 批量逐个修改
        private void BatchOneByOne(MessageHelper msgHelper , string ids)
        {
            string brandIds = Request.Form["selBrand"];
            string status = Request.Form["selStatus"];
            string actives = Request.Form["selActive"];
            string discounts = Request.Form["tbDiscount"];
            string stocks = Request.Form["tbStock"];
            string[] saleds = Request.Form.GetValues("tbSaleD");
            string[] salehs = Request.Form.GetValues("tbSaleH");
            string[] salems = Request.Form.GetValues("tbSaleM");

            int i;
            float f;
            DateTime d;

            // 检查输入的数据
            foreach (string s1 in Request.Form.GetValues("tbDiscount"))
            {
                if (!msgHelper.MustFloat(s1 , 2 , out f)) { break; }
            }

            foreach (string s2 in Request.Form.GetValues("tbStock"))
            {
                if (!msgHelper.MustInt(s2 , 1 , out i)) { break; }
            }

            foreach (string s3 in Request.Form.GetValues("tbSaleD"))
            {
                if (!msgHelper.MustDateTime(s3 , 5 , out d)) { break; }
            }

            foreach (string s4 in Request.Form.GetValues("tbSaleH"))
            {
                if (msgHelper.MustInt(s4 , 3 , out i))
                {
                    if (i < 0 || i > 24)
                    {
                        msgHelper.AddMessage(3);
                        break;
                    }
                }
            }

            foreach (string s5 in Request.Form.GetValues("tbSaleM"))
            {
                if (msgHelper.MustInt(s5 , 4 , out i))
                {
                    if (i < 0 || i > 60)
                    {
                        msgHelper.AddMessage(4);
                        break;
                    }
                }
            }

            // 组合上架日期
            if (msgHelper.IsValid)
            {
                string saleDateTimes = string.Empty;
                for (i = 0 ; i < saleds.Length ; i++)
                {
                    saleDateTimes += string.Format(",{0}" ,
                        DateTime.Parse(saleds[i])
                            .AddHours(int.Parse(salehs[i]))
                            .AddMinutes(int.Parse(salems[i])));
                }
                saleDateTimes = saleDateTimes.Trim(',');

                int result = _productPreView.Batch(ids , stocks , discounts ,
                    saleDateTimes , status , brandIds , actives);
                if (result != 1) { msgHelper.AddMessage(7); }
            }
        }

        // 批量统一修改
        private void BatchTogether(MessageHelper msgHelper , string ids)
        {
            string cbac = Request.Form["cbAction"];
            msgHelper.Required(cbac , 8);

            int stock = 0 , brand = 0;
            float discount = 1;
            DateTime saleTime = DateTime.Now;
            ProductStatus status = ProductStatus.Normal;
            // 检查输入的数据
            if (msgHelper.IsValid)
            {
                foreach (string s in Request.Form.GetValues("cbAction"))
                {
                    switch ((ProductBatchActionType)(int.Parse(s)))
                    {
                        case ProductBatchActionType.Status:
                            status = (ProductStatus)int.Parse(Request.Form["selStatus"]);
                            break;
                        case ProductBatchActionType.Active:
                            break;
                        case ProductBatchActionType.UpdateStock:
                            msgHelper.MustInt(Request.Form["tbStock"] , 1 , out stock);
                            break;
                        case ProductBatchActionType.UpdateSaleTime:
                            DateTime d;
                            int h , m;
                            if (msgHelper.MustInt(Request.Form["tbSaleH"] , 3 , out h))
                            {
                                if (h < 0 || h > 24)
                                {
                                    msgHelper.AddMessage(3);
                                }
                            }

                            if (msgHelper.MustInt(Request.Form["tbSaleM"] , 4 , out m))
                            {
                                if (m < 0 || m > 60)
                                {
                                    msgHelper.AddMessage(4);
                                }
                            }

                            if (!msgHelper.MustDateTime(Request.Form["tbSaleD"] , 5 , out d))
                            {
                                break;
                            }

                            saleTime = d.AddHours(h).AddMinutes(m);
                            break;
                        case ProductBatchActionType.UpdateDiscount:
                            msgHelper.MustFloat(Request.Form["tbDiscount"] , 2 , out discount);
                            break;
                        case ProductBatchActionType.UpdateBrand:
                            brand = int.Parse(Request.Form["selBrand"]);
                            break;
                    }
                }
            }
            if (msgHelper.IsValid)
            {
                int result = _productPreView.Batch(ids , cbac , stock , discount , saleTime , status , brand);
                if (result != 1) { msgHelper.AddMessage(7); }
            }
        }



        public ActionResult SelectProduct(
            [DefaultValue(1)]int number //页码
            , [DefaultValue(1)]int status //状态
            , [DefaultValue(0)]int classId //所属分类
            , [DefaultValue("")]string key //搜索关键字
            )
        {
            ProductList(number , status , classId , key);
            return View();
        }
    }
}
